package com.jay.tools.utils;

import android.app.Activity;
import android.content.Context;

import java.util.Stack;

public class ActivityManager {

    private static ActivityManager instance;

    private ActivityManager() {
    }

    /**
     * 单一实例
     */
    public static ActivityManager getInstance() {
        if (instance == null) {
            instance = new ActivityManager();
        }
        return instance;
    }

    /**
     * Activity栈集合
     */
    private static Stack<Activity> activityStack;

    /**
     * @param activity
     * @des 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * @return
     * @des 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * @des 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * @param activity
     * @des 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * @param clazz
     * @des 结束指定类名的Activity
     */
    public void finishActivity(Class<?> clazz) {
        if (null != activityStack && activityStack.size() > 0) {
            for (int i = 0; i < activityStack.size(); i++) {
                Activity activity = activityStack.get(i);
                if (activity.getClass().equals(clazz)) {
                    finishActivity(activity);
                }
            }
        }
    }

    /**
     * @des 结束所有Activity
     */
    public void finishAllActivity() {
        if (null != activityStack && activityStack.size() > 0) {
            for (int i = 0, size = activityStack.size(); i < size; i++) {
                if (null != activityStack.get(i)) {
                    activityStack.get(i).finish();
                }
            }
            activityStack.clear();
        }
    }

    /**
     * @param context
     * @des 结束所有Activity并退出程序，再重启程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            // 重启应用
            android.app.ActivityManager activityManager = (android.app.ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.restartPackage(context.getPackageName());
            exitApplication();
        } catch (Exception e) {
        }
    }

    /**
     * 退出程序
     */
    public void exitApplication() {
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}